﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileApp
{
    public static class Log
    {
        private static string logFile = "日志.txt";
        static readonly string backupDir = $"{Environment.CurrentDirectory}/log";
        private static StreamWriter writer;
        private static FileStream fileStream = null;

        public static void log(string MethodName, string info)
        {
            try { BackupAndRecreateWhileNewDay(); } catch { }
            try
            {
                string line = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + " " + MethodName + " " + info;
                AppendLine(line);
            }
            catch { }
        }
        static void AppendLine(string line)
        {
            FileInfo fileInfo = new FileInfo(logFile);
            using (FileStream fs = fileInfo.Exists ? fileInfo.Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite) : fileInfo.Create())
            {
                using (StreamWriter sr = new StreamWriter(fs, Encoding.GetEncoding(936)))
                {
                    sr.WriteLine(line);
                    sr.Close();
                }
                fs.Close();
            }
        }
        public static void CreateDirectory(string infoPath)
        {
            DirectoryInfo directoryInfo = Directory.GetParent(infoPath);
            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }
        }
        //新的一天则备份旧日志文件,重建新日志文件
        static void BackupAndRecreateWhileNewDay()
        {
            FileInfo info = new FileInfo(logFile);
            if (DateTime.Now.DayOfYear != info.LastWriteTime.DayOfYear)
            {
                if (!Directory.Exists(backupDir))
                {
                    Directory.CreateDirectory(backupDir);
                }
                string backupPath = $"{backupDir}/{Path.GetFileNameWithoutExtension(logFile)}-{info.LastWriteTime.ToString("yyyyMMdd")}{Path.GetExtension(logFile)}";
                File.Move(logFile, backupPath);
                File.Create(logFile).Close();

                DelOtherFile();
            }
        }

        public static void WriteErrToLog(string msg)
        {
            string timeString = DateTime.Now.ToString("yyyyMMdd");
            string fileName = System.IO.Path.Combine(backupDir, $"异常-{timeString}.log");

            if (!Directory.Exists(backupDir))
            {
                Directory.CreateDirectory(backupDir);
            }

            string errMsg = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} --> \n" + msg;
            WriteCSV(fileName, errMsg);
        }

        public static void WriteCSV(string filePath, string errMes)
        {
            FileInfo fileInfo = new FileInfo(filePath);
            using (FileStream fs = fileInfo.Exists ? fileInfo.Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite) : fileInfo.Create())
            {
                using (StreamWriter sr = new StreamWriter(fs, Encoding.GetEncoding(936)))
                {
                    sr.WriteLine(errMes);
                    sr.Close();
                }
                fs.Close();
            }
        }

        public static void DelOtherFile()
        {
            Task.Run(() =>
            {

                try
                {
                    //定义一个DirectoryInfo对象
                    DirectoryInfo di = new DirectoryInfo(backupDir);
                    List<FileInfo> list = new List<FileInfo>();

                    //通过GetFiles方法,获取di目录中的所有文件的大小
                    foreach (FileInfo fi in di.GetFiles())
                    {
                        list.Add(fi);
                    }

                    if (list.Count > 30)
                    {
                        var temps = list.OrderByDescending(o => o.LastWriteTime).Skip(10).ToList();
                        foreach (FileInfo fi in temps)
                        {
                            try
                            {
                                File.Delete(fi.FullName);
                            }
                            catch
                            {

                            }
                        }
                    }
                }
                catch
                {

                }
            });
        }
    }
}
